package com.qingxin.sys.filter;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.SysPermission;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.SysPermissionService;
import com.qingxin.sys.service.SysUserService;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.JsonUtil;
import com.qingxin.sys.utils.ResponseUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.sys.verifier.Form;
import com.qingxin.sys.verifier.FormFactory;
import com.qingxin.sys.verifier.VerifyMsg;


/**
 * 请求拦截器
 * @author Administrator
 *
 */
public class RequestInterceptor extends BaseInterceptor {
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysPermissionService sysPermissionService;
	
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	request.setAttribute("_pass_request_interceptor", 1);
    	
    	//是否拦截
    	if(!shouldIntercept(request)){
    		//验证表单
        	if(!validateForm(request, response, handler)){
        		return false;
        	}
        	return true;
    	}
    	
        //登录验证
    	String userid = (String) request.getSession().getAttribute(SystemCfg.SESSION_LOGIN_USERID);
    	if(userid != null){
    		LoginUser loginUser = sysUserService.getLoginUser(userid);
    		if(loginUser != null){
    			//验证权限
    			if(!checkPermissions(request, response, handler, loginUser)){
					return false;//没有权限
				}
    			//验证表单
    	    	if(!validateForm(request, response, handler)){
    	    		return false;
    	    	}
    			return true;//验证通过
    		}
    	}

    	//登录验证失败
    	String servletPath = request.getServletPath();
    	if(servletPath.endsWith(".do")){
    		if(servletPath.matches("/(\\w+)/index\\.do.*")){
    			String login_kind = servletPath.replaceAll("/(\\w+)/index\\.do.*", "$1");
    			request.getSession().setAttribute("login_kind", login_kind);
    		}
    		String path = request.getContextPath();
    		ResponseUtil.render(response,"text/html; charset=UTF-8", "<script>top.location.href = '" + path + "/public/timeout.do';</script>");
    	}else {
    		ResponseUtil.renderJson(response, JsonUtil.toJSON(new SysError("请先登录后再进行该操作")));
		}
    	return false;
    	
    }
    

//    //URL权限验证
//    private boolean checkPermission(HttpServletRequest request, HttpServletResponse response, Object handler, LoginUser loginUser){
//    	if(SystemCfg.isAdminUser(loginUser)){
//    		return true;
//    	}
//    	String url = request.getServletPath();
//    	SysPermission permission = sysPermissionService.getPermissionByUrl(url);
//    	if(permission != null){
//    		Set<String> rights = sysPermissionService.getUserPermissionCodes(loginUser.getUserid());
//    		if(!rights.contains(permission.getPer_code().toUpperCase())){
//    			ResponseUtil.renderJson(response, JsonUtil.toJSON(new SysError("抱歉！您没有权限进行该操作.")));
//    			return false;
//    		}
//    	}
//    	return true;
//    }
    
    //URL权限验证
    private boolean checkPermissions(HttpServletRequest request, HttpServletResponse response, Object handler, LoginUser loginUser){
    	if(SystemCfg.isAdminUser(loginUser) || SystemCfg.isSystemAdminUser(loginUser)){
    		return true;
    	}
    	String url = request.getServletPath();
    	List<SysPermission> permissions = sysPermissionService.getPermissionsByUrl(url);
    	if(permissions != null && permissions.size() > 0){
    		Set<String> rights = sysPermissionService.getUserPermissionCodes(loginUser.getUserid());
    		boolean matched = false;
    		for(SysPermission permission : permissions){
    			if(matchUrl(permission.getUrl(), url, request)){
    				if(rights.contains(permission.getPer_code().toUpperCase())){
    					matched = true;
						break;
					}
    				
    			}
    		}
    		if(!matched){
    			ResponseUtil.renderJson(response, JsonUtil.toJSON(new SysError("抱歉！您没有权限进行该操作.")));
    			return false;
    		}
    	}
    	return true;
    }
    
    private boolean matchUrl(String permUrl, String url, HttpServletRequest request){
    	int index = permUrl.indexOf("?");
    	if(index == -1){
    		if(permUrl.equalsIgnoreCase(url)){
    			return true;
    		}
    	}else{
    		String query = permUrl.substring(index + 1);
    		permUrl = permUrl.substring(0, index);
    		if(permUrl.equalsIgnoreCase(url)){
    			String[] params = query.split("&");
    			boolean allEquals = true;
    			for(int i=0; i<params.length; i++){
    				String param = params[i];
    				int index2 = param.indexOf("=");
    				String name = param.substring(0, index2);
					String value = param.substring(index2 + 1);
					String reqValue = request.getParameter(name);
					if(!value.equals(reqValue)) {
						allEquals = false;
						break;
					}
    			}
    			if(allEquals){
					return true;
				}
			}
    	}
		return false;
	}
    
    
    
    //验证表单
    private boolean validateForm(HttpServletRequest request, HttpServletResponse response, Object handler){
    	String servletPath = request.getServletPath();
    	if(servletPath.endsWith(".json")){
    		String action = servletPath;
    		if(action.indexOf("/") != -1){
    			action = action.substring(action.lastIndexOf("/") + 1);
    		}
    		if(action.startsWith("save") || action.startsWith("update") || action.startsWith("del")){//仅针对以save、update、del开头的请求进行验证
    			Form form = null;
    			String verifier_action = request.getParameter("_verifier_action");
    			if(StringUtils.isNotEmpty(verifier_action)){
    				form = FormFactory.getForm(action);
    				if(form == null){
    					ResponseUtil.renderJson(response, JsonUtil.toJSON(new SysError("参数错误")));
    					return false;
    				}
    			}else {
    				action = servletPath;
    				form = FormFactory.getForm(action);
				}
    			if(form != null){
    				boolean pass = form.verify(request);
    				if(!pass){
    					VerifyMsg msg = form.getFirstMessage();
    					if(msg == null){
    						ResponseUtil.renderJson(response, JsonUtil.toJSON(new SysError("参数错误")));
    					}else {
							String errorMessage = msg.getLabelMessage(false);
							ResponseUtil.renderJson(response, JsonUtil.toJSON(
									new SysError(msg.getId(), StringUtils.isEmpty(errorMessage)?"参数错误":errorMessage)));
						}
    					return false;
    				}
    			}
    		}
    	}
    	return true;
    }
    
    
}